package org.qydjk.console.controller.card;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.StoreCard;
import org.qydjk.common.pojo.StoreCardCategory;
import org.qydjk.common.pojo.WechatPublicInteraction;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.ExcelUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.console.service.IStoreCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

//体检卡
@Controller
@RequestMapping("/card")
public class StoreCardController extends BaseController {

    @Autowired
    private  IStoreCardService cardService;

    @RequestMapping("/gotoCardCategory.do")
    public String gotoCardCategory(){
        return "card/cardCategory";
    }
    /**
     * 体检卡种类数据表格ajax
     * @return
     */
    @RequestMapping("/cardClassdg.do")
    @ResponseBody
    public Object cardCategory(Integer page, Integer rows) throws Exception {
        try {
            HibernatePage pager = new HibernatePage(page,rows);
            String sql="select * from qy_store_card_category";
            List<StoreCardCategory>  classifylistList =baseService.findBySQL(sql, StoreCardCategory.class,pager);
            int total = baseService.getRecordCountHQL("select count(c.id) from StoreCardCategory c");
            return new EasyUIResponse(total,classifylistList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 体检卡数据表格ajax
     * @return
     */
    @RequestMapping("/carddg.do")
    @ResponseBody
    public Object carddg(Integer page,Integer rows,Integer classId,String keyWord) throws Exception {
        try {
            HibernatePage pager = new HibernatePage(page,rows);
            String sql="select c.*,s.name as shopName from qy_store_card c\n" +
                    "left join qy_seller s on c.receive_seller_id = s.id" +
                    " where 1=1";
            String countsql = "select count(c.id) from qy_store_card c where 1=1";
            if(classId!=null){
                sql+=" and c.store_card_category_id = "+classId;
                countsql+=" and c.store_card_category_id = "+classId;
            }
            if(keyWord!=null&&!"".equals(keyWord)){
                sql+=" and c.code like '%"+keyWord+"%'";
                countsql+=" and c.code like '%"+keyWord+"%'";
            }
            List<Map<String,Object>>  cardList =baseService.findMapBySQL(sql,pager);
            int total = baseService.getRecordCountSQL(countsql);
            return new EasyUIResponse(total,cardList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加体检卡种类
     */
    @RequestMapping("/cardcatadd.do")
    @ResponseBody
    public Object classadd(StoreCardCategory cardCategory){
        try {
            cardCategory.setTotalRepertory(0);    //总库存
            cardCategory.setRemainRepertory(0);  //剩余数量
            cardCategory.setSell(0);          //已售数量
            cardCategory.setActived(0);  //激活数量
            cardCategory.setStatus(1);    //默认启用
            cardCategory.setCreateTime(new Date());//创建时间
            cardCategory.setUpdateTime(new Date()); //修改时间
            baseService.save(cardCategory);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 编辑体检卡种类
     */
    @RequestMapping("/cardcatedit.do")
    @ResponseBody
    public Object cardcatedit(StoreCardCategory cardCategory){
        cardCategory.setUpdateTime(new Date());//修改时间
        try {
            StoreCardCategory oldcartcat = baseService.get(StoreCardCategory.class,cardCategory.getId());
            cardCategory.setUpdateTime(new Date());
            BeanUtil.copyProperties(cardCategory,oldcartcat);
            baseService.saveOrUpdate(oldcartcat);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 修改卡种类适用商家
     * @param classId
     * @param shopId
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping("/chooseshop.do")
    @ResponseBody
    public Object chooseshop(Integer classId,Integer shopId,Integer type) {
        try {
                StoreCardCategory category = baseService.get(StoreCardCategory.class,classId);
                String shopids = category.getSuitSellerIds();
                if(type==1){//删除
                    shopids=shopids.replace(shopId.toString()+",","");
                }else{//添加
                    if(StringUtil.isEmptyOrNull(shopids)){
                            shopids=","+shopId.toString()+",";
                    }else{
                        shopids+=shopId.toString()+",";
                    }
                }
                category.setSuitSellerIds(shopids);
                category.setUpdateTime(new Date());
            baseService.update(category);
                return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 自动补全 机构信息
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object autoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        try {
        String query = request.getParameter("query");
        query = StringUtil.iosToUTF8(query).trim();
            if("".equals(query)){return null;}
        System.out.println(query);
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
        String sql = "SELECT name as `value`,concat(id,'') AS `data` FROM qy_seller WHERE status=1 and verify_type=1 and name LIKE '%"+ query +"%'";
        list = baseService.findBeanBySQL(sql,AutoCompleteBean.class,new HibernatePage(1,10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }

    /**
     * 添加或者删除领取机构
     * @param cardids
     * @param shopId
     * @return
     */
    @RequestMapping("/editshopcards.do")
    @ResponseBody
    public Object editshopcards(String cardids,Integer shopId){
        try {
            String checksql = "select count(*) from qy_store_card where (type <>0 or receive_seller_id is not null) and id in ("+cardids+")";
            int checknum = baseService.getRecordCountSQL(checksql);
            if(checknum>0){
                return renderError("存在已领取或已售的卡，无法领取~");
            }
            String updatesql = "update qy_store_card set receive_seller_id = "+shopId+",update_time=now() where id in ("+cardids+")";
            baseService.excuteSQL(updatesql);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 删除卡种类
     * @param id
     * @return
     */
    @RequestMapping("/cardcatdelete.do")
    @ResponseBody
    public Object cardcatdelete(Integer id){
        try {
           int delret = cardService.delcardClass(id);
            if(delret==1){
                return renderSuccess();
            }else{
                return renderError("该种类下存在已领取或已售的卡，无法删除~");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 体检卡种类下拉数据
     * @return
     * @throws Exception
     */
    @RequestMapping("/getcardclass.do")
    @ResponseBody
    public Object getcardclass() throws Exception {
        List<StoreCardCategory> categoryLists = baseService.findBySQL("select * from qy_store_card_category",StoreCardCategory.class);
        if (categoryLists != null) {
            return categoryLists;
        }
        return null;
    }

    /**
     * 添加体检卡
     * @return
     */
    @RequestMapping("/cardadd.do")
    @ResponseBody
    public Object cardadd(StoreCard storeCard){
        try {
            int res = cardService.addCard(storeCard);
            if(res==2){
                return renderError("卡号已存在");
            }
            return renderSuccess();
        } catch (Exception e) {
            return renderError(e.getMessage());
        }
    }


    //批量添加储值卡
    @RequestMapping("/uploadStoreCard.do")
    @ResponseBody
    public Object uploadStoreCard() {
        try {
            //文件上传的三部曲
            //创建工厂
            DiskFileItemFactory factoy=new DiskFileItemFactory();
            //创建解析器
            ServletFileUpload sfu=new ServletFileUpload(factoy);
            //设置上传文件的大小
            sfu.setFileSizeMax(20*1024);
            //解析request
            List<FileItem> list=sfu.parseRequest(request);
            Map<String, Object> datas = new HashMap<String, Object>();
            String cardcatId = "";
            for (FileItem item:  list){
                if(item.getFieldName().equals("cardcatId")){
                    cardcatId = item.getString("utf-8");
                }if(item.getFieldName().equals("excelFile")){
                    datas = ExcelUtil.getDataFromExcel(item.getInputStream());
                }
            }
           if (!"OK".equals(datas.get("msg").toString())) {
               return renderError(datas.get("msg").toString());
            }
            String codeStr = datas.get("codestr").toString();
            String testsql = "select count(code) from qy_store_card where code in (" + codeStr.substring(1, codeStr.length() - 1) + ")";
            int haveCount = baseService.getRecordCountSQL(testsql);
            if (haveCount == 0) {
                StoreCardCategory category = baseService.get(StoreCardCategory.class,Integer.parseInt(cardcatId.toString()));
                cardService.addCardfromExcel(category, (List<Map>) datas.get("content"));
                return renderSuccess();
            } else {
                return renderError("excel数据中存在已有卡号！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 修改体检卡
     * @param storeCard
     * @return
     */
    @RequestMapping("/cardedit.do")
    @ResponseBody
    public Object cardedit(StoreCard storeCard) {
        try {
            cardService.updateCard(storeCard);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 撤销领取体检卡
     * @param id
     * @return
     */
    @RequestMapping("/cancelShop.do")
    @ResponseBody
    public Object cancelShop(int id) {
        try {
            StoreCard card = baseService.get(StoreCard.class,id);
            card.setReceiveSellerId(null);
            baseService.saveOrUpdate(card);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 删除体检卡
     * @param id
     * @return
     */
    @RequestMapping("/carddelete.do")
    @ResponseBody
    public Object carddelete(Integer id){
        try {
            cardService.delCard(id);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    @RequestMapping("/eidtcardClassShop.do")
    public String eidtcardClassShop(Integer cardId,boolean multiple){
        request.setAttribute("multiple",multiple);
        request.setAttribute("cardId",cardId);
        return "card/cardcatEdit_shop";
    }

    /**
     *  体检卡机构列表数据ajax
     * @param page      页数
     * @param rows       行数
     * @param classId   卡种类ID
     * @param flag      true 已选择 false 未选择
     *  @param keyWord    搜索
     * @return
     */
    @RequestMapping("/selectShops.do")
    @ResponseBody
    public Object selectShops(Integer page,Integer rows,Integer classId,Integer flag,String keyWord)  {
        if(classId==null){
            return new EasyUIResponse(0,null);
        }
        try {
            HibernatePage pager = new HibernatePage(page,rows);
            StoreCardCategory category =baseService.get(StoreCardCategory.class,classId);
            String shopids = category.getSuitSellerIds();
            List<Map<String, Object>>  shoplist=null;
            int total=0;
            String sql = "";
            String countsql = "";
            if(flag==1){//体检卡分类支持机构
                if(equals(shopids)||shopids==null||",".equals(shopids)){
                    return new EasyUIResponse(0,null);
                }else{
                    shopids = shopids.substring(1,shopids.length()-1);
                    sql = "select id,name,1 as type from qy_seller where status=1 and verify_type=1 and id in ("+shopids+")";
                    countsql = "select count(*) from Seller where status=1 and verifyType=1 and id in ("+shopids+")";
                }
            }else{//不支持机构
                if("".equals(shopids)||shopids==null){
                    sql = "select id,name,2 as type from qy_seller where status=1 and verify_type=1";
                    countsql = "select count(*) from Seller where status=1 and verifyType=1";
                }else{
                    shopids = shopids.substring(1,shopids.length()-1);
                    sql = "select id,name,2 as type from qy_seller where status=1 and verify_type=1 and id not in ("+shopids+")";
                    countsql = "select count(*) from Seller where status=1 and verifyType=1 and id not in ("+shopids+") ";
                }
            }
            //追加搜索关键字
            if(!"".equals(keyWord)&&keyWord!=null){
                sql+=" and name like '%"+keyWord+"%'";
                countsql+=" and name like '%"+keyWord+"%'";
            }
            sql+=" order by name";
            shoplist = baseService.findMapBySQL(sql,pager);
            total = baseService.getRecordCountHQL(countsql);
            return new EasyUIResponse(total,shoplist);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
    @RequestMapping("/productList.do")
    @ResponseBody
    public Object productList(){
        try {
            List<Map<String,Object>> productId = baseService.findMapBySQL("select name,concat(id,'') as id from qy_product where type<>0");
            return productId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
